package org.csu.mypetstore.controller;

import org.csu.mypetstore.domain.Account;
import org.csu.mypetstore.domain.Cart;
import org.csu.mypetstore.domain.Item;
import org.csu.mypetstore.persistence.ItemMapper;
import org.csu.mypetstore.service.CartService;
import org.csu.mypetstore.service.CatalogService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;

import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import sun.reflect.CallerSensitive;

import javax.servlet.http.HttpSession;

@Controller
@RequestMapping("/cart")
public class CartController {
    @Autowired
    CatalogService catalogService;

    @Autowired
    CartService cartService;

    @GetMapping("/viewCart")
    public String viewCart(){
        return "/cart/Cart";
    }

    @GetMapping("/addItemToCart")
    public String addItemToCart(String workingItemId, HttpSession session){

        Cart cart=(Cart)session.getAttribute("cart");

        if(cart==null){
            cart=new Cart();
        }

        if(cart.containsItemId(workingItemId)){
            cart.incrementQuantityByItemId(workingItemId);
        }
        else {
            boolean isInStock = catalogService.isItemInStock(workingItemId);
            Item item = catalogService.getItem(workingItemId);
            cart.addItem(item,isInStock);
        }

        ////////////////////////////////数据库购物车
        Account account = (Account) session.getAttribute("account");
        String itemId = workingItemId;
        String username = account.getUsername();
        int quantity = cart.getQuantityByItemId(itemId);
        cartService.saveItemToDatabase(itemId,username,quantity);
        /////////////////////////////////

        session.setAttribute("cart",cart);

        return "/cart/Cart";
    }

    @GetMapping("/removeItemFromCart")
    public String removeItemFromCart(String workingItemId, HttpSession session, Model model){
        Cart cart = (Cart)session.getAttribute("cart");

        Item item = cart.removeItemById(workingItemId);

        Account account = (Account) session.getAttribute("account");
        String itemId = workingItemId;
        String username = account.getUsername();
        cartService.deleteItemFromDatabase(itemId,username);

        if(item==null){
            model.addAttribute("msg","Attempt to remove null CartItem from Cart");
            return "/common/Error";
        }
        else {
            return "/cart/Cart";
        }
    }

}
